//
//  STDSParticle.h
//  STDSRenderSDKIOS
//
//  Created by 陈学明 on 2023/7/10.
//

#ifndef STDSParticle_h
#define STDSParticle_h

#include <random>
#include <time.h>
#include <memory>
#include <vector>
#include <stdio.h>

using namespace std;
// 单个粒子
struct STDSParticleUnit {
    float px{0.0};// 位置, mask 区域内的一个随机坐标
    float py{0.0};
    float pz{0.0};
    float tx{0.0}; // 纹理坐标
    float ty{0.0};
    float lifestart{0.0};// 生命开始时间, -1.0~3.0 的一个随机值
    float duration{0.0};// 粒子生命时长, 0.0～5.0 的一个随机值
    
    float angle{0.0}; // 粒子旋转角度
    float speed{0.0};// 运动速度增益, 0.0～1.0 的随机值
    float rotateSpeed{0.0};// 粒子旋转速度
    
    STDSParticleUnit(float x, float y, float z):px(x), py(y), pz(z) {
        tx = x;
        ty = y;
        px = (x - 0.5) * 2.0;
        py = (y - 0.5) * 2.0;
        pz = (z - 0.5) * 2.0;
        
        mt19937 gen((unsigned int) time(nullptr));
        normal_distribution<double> dis(0.0, 1.0);
        speed = dis(gen);
        duration = dis(gen) * 5.0;
        lifestart = dis(gen) * 4.0 - 1.0;
        angle = dis(gen) * 360.0;
        rotateSpeed = dis(gen);
    }
    
    int getLength() {
        return 10;
    }
    
    ~STDSParticleUnit() {
        
    }
};

// 粒子系统
class STDSParticleKit {
    
public:
    STDSParticleKit(float density) {
        mDensity = density;
    }
    
    ~STDSParticleKit() {
        
    }
    
    // 构建随机粒子
    void build(const char *maskData, int width, int height) {
        mParticles.clear();
        // 粒子总数
        int num = (width/mDensity)*(height/mDensity);
        mt19937 gen((unsigned int) time(nullptr));
        normal_distribution<double> dis(0.0, 1.0);
        for (int i = 0; i < num; i++) {
            int x = floor(dis(gen) * width);
            int y = floor(dis(gen) * height);
            int index = y * height + x;
            if (index >= width*height) {
                continue;
            }
            char pixel = maskData[index];
            if (pixel < 50) {
                continue;
            }

            STDSParticleUnit particle(float(x)/float(width), float(y)/float(height), 0.0);
            mParticles.push_back(particle);
        }
    }
    
    vector<STDSParticleUnit> getVertex() {
        return mParticles;
    }
    
    int getUnitLength() {
        return 8;
    }
    
    unsigned long getVertexCount() {
        return mParticles.size();
    }
private:
    vector<STDSParticleUnit> mParticles; // 粒子数组
    int mDensity{5}; // 粒子密度，每 5x5 个像素产生一个粒子
};

#endif /* STDSParticle_h */
